import React, { memo, useRef, useState } from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { HeaderWrapper, SearchAreaWrapper } from './style';
import HeaderLeft from './c-cpns/header-left';
import HeaderCenter from './c-cpns/header-center';
import HeaderRight from './c-cpns/header-right';
import classNames from 'classnames';
import useScrollPosition from 'src/hooks/useScrollPosition';
import { ThemeProvider } from 'styled-components';

// 不共享 更容易操作
const AppHeader = memo(() => {
  // 记录定义组件中的状态
  const [isSearch, setIsSearch] = useState(false);
  const isFixed = useSelector((state) => state.main.headerConfig.isFixed, shallowEqual);
  const topAlpha = useSelector((state) => state.main.headerConfig.topAlpha, shallowEqual);

  function searchBarClickHandle() {
    setIsSearch(true);
  }
  function coverSearchAreaHandle() {
    setIsSearch(false);
  }

  // 监听滚动
  const { scrollY } = useScrollPosition();
  const prevY = useRef(0);

  // 正常滚动下 搜索框没有弹出来 记录scrollY
  if (!isSearch) prevY.current = scrollY;

  // 在弹出搜索功能的情况下 滚动的距离大于之前记录的距离的30
  if (isSearch && Math.abs(prevY.current - scrollY) > 30) coverSearchAreaHandle();
  // if (isSearch) {
  //   function distanceAbs(prev, cur) {
  //     return Math.abs(prev - cur);
  //   }
  //   const distance = distanceAbs(prevY.current, scrollY);
  //   console.log(distance);
  //   if (distance > 10) {
  //     setIsSearch(false);
  //   }
  // }
  // console.log(`scrollY${scrollY} - prevY.current${prevY.current}=${scrollY - prevY.current}`);

  // 透明度
  const isAlpha = topAlpha && scrollY === 0;
  return (
    <ThemeProvider theme={{ isAlpha }}>
      <HeaderWrapper className={classNames({ fixed: isFixed })} $isAlpha={isAlpha}>
        <div className="content">
          <div className="normal-header">
            <HeaderLeft />
            <HeaderCenter isSearch={isAlpha || isSearch} searchBarClick={(e) => searchBarClickHandle()} />
            <HeaderRight />
          </div>

          <SearchAreaWrapper $isSearch={isAlpha || isSearch}></SearchAreaWrapper>
        </div>
        {isSearch && <div className="cover" onClick={(e) => coverSearchAreaHandle()}></div>}
      </HeaderWrapper>
    </ThemeProvider>
  );
});

export default AppHeader;
